'use strict';
let { Sequelize, DataTypes } = require("sequelize");

//实例化
let sequelize = new Sequelize('designer', 'postgres', 'qq_112358', {
    host: '8.129.116.184',
    dialect: 'postgres'
});

//模型定义
function defineModel(name, obj) {
    let prop = {};
    prop.id = {
        type: DataTypes.BIGINT,
        primaryKey: true,
        autoIncrement: true
    }

    for (let i in obj) {
        prop[i] = obj[i];
    }
    prop.createdAt = {
        type: DataTypes.BIGINT,
        allowNull: false
    }
    prop.updatedAt = {
        type: DataTypes.BIGINT,
        allowNull: false
    }
    prop.version = {
        type: DataTypes.INTEGER,
        allowNull: false
    }
    prop.remarks = {
        type: DataTypes.STRING(800),
        allowNull: true
    }

    let model = sequelize.define(name, prop, {
        tableName: name,
        timestamps: false,//生成新的一个时间戳
        hooks: {
            beforeValidate: function (obj) {
                let newTime = Date.now();
                if (obj.isNewRecord) {
                    obj.createdAt = newTime,
                        obj.updatedAt = newTime,
                        obj.version = 0
                } else {
                    obj.updatedAt = newTime,
                        obj.version += 1
                }
            }
        }

    });
    return model;
}
//暴露数据类型、sequelize、模型定义
let obj = {
    DataTypes,
    sequelize,
    defineModel
}

module.exports = obj;